﻿using Digitalmes.Application.Sys.Users.Queries;

namespace Digitalmes.WebApi.Endpoints;

/// <summary>
/// 动态路由终结点。
/// </summary>
public sealed class RouteEndpoint : EndpointGroupBase
{
    public override void Map(WebApplication app)
    {
        app.MapGroup(this)
            .RequireAuthorization()
            .MapGet(GetRoutesAsync, "async-routes");
    }

    /// <summary>
    /// 获取动态路由信息。
    /// </summary>
    /// <returns></returns>
    public async Task<IApiResult> GetRoutesAsync(ICurrentUser currentUser, ISender sender)
    {
        if (currentUser.UserId is null)
        {
            return ApiResult.Bad();
        }

        var result = (await sender.Send(new GetMenusOfUserQuery(currentUser.UserId.Value))).Value;
        IEnumerable<RouteViewModel> FormatRoute(long parentId)
        {
            foreach (var (menu, roles) in result.Where(s => s.menu.ParentId == parentId && s.menu.MenuType != MenuTypeEnum.Button).OrderBy(s => s.menu.Rank))
            {
                RouteViewModel route = new()
                {
                    Path = menu.Path,
                    Name = menu.Name,
                    Redirect = menu.Redirect,
                    Component = menu.Component,
                    Meta = new RouteMetaViewModel
                    {
                        Rank = menu.Rank,
                        Title = menu.Title,
                        Icon = menu.Icon,
                        ExtraIcon = menu.ExtraIcon,
                        ShowLink = menu.ShowLink,
                        ShowParent = menu.ShowParent,
                        Roles = roles,
                        Auths = result.Where(s => s.menu.ParentId == menu.Id && s.menu.MenuType == MenuTypeEnum.Button && s.menu.Auths != null)
                            .Select(s => s.menu.Auths!)
                            .ToArray(),
                        KeepAlive = menu.KeepAlive,
                        FrameSrc = menu.FrameSrc,
                        FrameLoading = menu.FrameLoading,
                        Transition = new RouteTransitionViewModel
                        {
                            EnterTransition = menu.EnterTransition,
                            LeaveTransition = menu.LeaveTransition,
                        },
                        HiddenTag = menu.HiddenTag,
                        ActivePath = menu.ActivePath,
                    },
                };

                // 没有 Children 时，默认值为 null。
                var children = FormatRoute(menu.Id).ToList();
                if (children.Count > 0)
                {
                    route.Children = children;
                }

                yield return route;
            }
        }

        List<RouteViewModel> routes = FormatRoute(0).ToList();
        return ApiResult.Ok(routes);
    }
}
